from sanic.exceptions import InvalidUsage


class SspErrorCode:
    """全局错误码"""

    paramsError = 40001
    """参数错误"""

    success = 0
    """请求成功"""


class SspCodeException(InvalidUsage):
    """构造请求错误的异常，统一输出结构

    Args:
        InvalidUsage (exception): 统一的400的错误
    """

    __CODE_MESSAGE = {
        0: "SUCCESS",
        40001: "参数错误",
    }
    """错误码对应的错误信息
    """

    def __init__(self, code: int, msg: str = None):
        """构造一个全局响应的 400 异常

        Args:
            code (int): 错误码, SspErrorCode
            msg (str): 错误信息
        """
        if msg is None and code in self.__CODE_MESSAGE:
            if code in self.__CODE_MESSAGE:
                msg = self.__CODE_MESSAGE[code]
            else:
                msg = ""
        super().__init__(message=msg)
        self.message = msg
        self.code = code

    def as_dict(self):
        """转换为字典"""
        return {"code": self.code, "message": self.message}
